package com.zcf.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zcf.common.json.Body;
import com.zcf.mapper.LargeMapper;
import com.zcf.pojo.Large;
import com.zcf.utils.Hutool;
import com.zcf.utils.UploadImgUtils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author loupeng
 * @since 2018-12-29
 */
@Controller
@RequestMapping("/large")
@ResponseBody
@CrossOrigin
public class LargeController {

	@Autowired
	LargeMapper largeMapper;

	/**
	 * 添加分类
	 * 
	 * @throws Exception
	 */
	public Body insert(Large large, MultipartFile[] file) throws Exception {
		large.setLargeId(Hutool.getId());
		String files = UploadImgUtils.uploadFiles(file);
		if (files != null && !"".equals(files)) {
			large.setImage(files);
		}
		return Body.newInstance("添加失败");
	}

	/**
	 * 查询大类
	 */
	@PostMapping("query")
	public Body query() {
		EntityWrapper<Large> we = new EntityWrapper<>();
		we.orderBy("position", true);
		List<Large> list = largeMapper.selectList(we);
		if (list.size() > 0) {
			return Body.newInstance(list);
		}
		return Body.newInstance("查无数据");
	}

	/**
	 * 修改大类
	 */
	@PostMapping("updateLarge")
	public Body updateLarge(Large large, MultipartFile[] file) throws Exception {
		Large large2 = new Large();
		EntityWrapper<Large> ew = new EntityWrapper<>();
		ew.eq("position", large.getPosition());
		large2 = large2.selectOne(ew);
		if (!large2.getLargeId().equals(large.getLargeId())) {
			return Body.newInstance(-1, "该位置已存在");
		}
		String files = UploadImgUtils.uploadFiles(file);
		if (files != null && !"".equals(files)) {
			large.setImage(files);
		}
		Boolean flag = large.updateById();
		if (flag) {
			return Body.newInstance(large);
		}
		return Body.BODY_500;
	}

	/**
	 * 删除大类
	 */
	public Body deledteLarge(String largeId) {
		Large large = new Large();
		String[] appid = largeId.split(",");
		Boolean falg = false;
		for (int i = 0; i < appid.length; i++) {
			large.setLargeId(appid[i]);
			falg = large.deleteById();
		}
		if (falg) {
			return Body.newInstance("关闭成功");
		}
		return Body.newInstance("关闭失败");
	}

	/**
	 * 根据id查询大类详情
	 */
	@PostMapping("queryOne")
	public Body queryOne(String largeId) {
		Large large = new Large();
		large.setLargeId(largeId);
		large = large.selectById();
		if (large != null) {
			return Body.newInstance(large);
		}
		return Body.BODY_500;
	}
}
